package com.itheima.service.impl.system;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.system.Permission;
import com.itheima.mapper.system.PermissionMapper;
import com.itheima.mapper.system.UserMapper;
import com.itheima.service.system.PermissionService;
import com.itheima.utils.IdUtil;
import com.itheima.utils.MapperUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class PermissionServiceImpl implements PermissionService {
    @Override
    public List<Permission> findByPage(int pageNum, int pageSize) {
        PermissionMapper mapper = MapperUtil.getMapper(PermissionMapper.class);
        PageHelper.startPage(pageNum,pageSize);
        return mapper.findAll();
    }

    @Override
    public void save(Permission permission) {
        PermissionMapper mapper = MapperUtil.getMapper(PermissionMapper.class);
        permission.setId(IdUtil.getId());
        permission.setCreateTime(new Date());
        mapper.save(permission);
    }

    @Override
    public Permission findById(String id) {
        PermissionMapper mapper = MapperUtil.getMapper(PermissionMapper.class);
        return mapper.findById(id);
    }

    @Override
    public void delete(String deleteId) {
        SqlSession session = MapperUtil.getSession();
        PermissionMapper mapper = session.getMapper(PermissionMapper.class);
        String[] split = deleteId.split(",");
        for (String id : split) {
            mapper.deletePermRoleByPid(id);
            session.commit();
            mapper.delete(id);
            session.commit();
        }
        session.close();
    }

    @Override
    public List<Permission> findAll() {
        PermissionMapper mapper = MapperUtil.getMapper(PermissionMapper.class);
        return mapper.findAll();
    }

    @Override
    public void deletePermission(String id) {
        SqlSession session = MapperUtil.getSession();
        PermissionMapper mapper = session.getMapper(PermissionMapper.class);
        mapper.deletePermRoleByPid(id);
        session.commit();
        mapper.delete(id);
        session.commit();
    }
}
